package menulogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenuRoleIdsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetMenuRoleIdsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuRoleIdsLogic {
	return &GetMenuRoleIdsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetMenuRoleIdsLogic) GetMenuRoleIds(in *syspb.GetMenuRoleIdsReq) (*syspb.GetMenuRoleIdsResp, error) {
	if in.GetId() == 0 {
		return &syspb.GetMenuRoleIdsResp{RoleIds: nil}, nil
	}

	enforcer := l.svcCtx.AdapterCasbin.SetCtxSession(l.ctx, nil).Enforcer
	policies := enforcer.GetFilteredNamedPolicy("p", 1, convertor.ToString(in.GetId()))

	// 数据处理
	var roleIds []int64
	for _, policy := range policies {
		val, _ := convertor.ToInt(policy[0])
		roleIds = append(roleIds, val)
	}

	return &syspb.GetMenuRoleIdsResp{RoleIds: roleIds}, nil
}
